//
//  CZStatusDetailController.swift
//  GZWeibo007
//
//  Created by 蓝文举 on 15/12/24.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

import SVPullToRefresh


class CZStatusDetailController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var comments: [CZComment]? {
        didSet {
            self.tableView.reloadData()
        }
    }

    func loadComments() {
        let max_id = self.comments?.last?.id ?? 0
        CZComment.loadComments(status!.id,max_id: max_id) { (comments, error) -> () in
            
            //停止转菊花
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                print("加载评论出错")
                return
            }
            if comments?.count == 0 {
                print("没有评论")
                return
            }
            if max_id > 0 {
                self.comments = self.comments! + comments!
                return
            }
            self.comments = comments
            self.tableView.showsInfiniteScrolling = true
        }
    }
    
    var status: CZStatus? {
        didSet {
            bottomView.commentButton.setTitle("评论", forState: UIControlState.Normal)
            bottomView.forwardButton.setTitle("转发", forState: UIControlState.Normal)
            bottomView.zanButton.setTitle("赞", forState: UIControlState.Normal)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
//        loadComments()
        
        navigationItem.title = "微博详情"
        prepareUI()
        
        
    }

    //MARK: - 准备UI
    func prepareUI() {
        
        view.addSubview(tableView)
        view.addSubview(bottomView)
        
        //添加约束
        let navBarHeight: CGFloat = 44
        let bottomViewHeight: CGFloat = 44
        let tableViewSize = CGSize(width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height - navBarHeight)
        tableView.ff_AlignInner(type: ff_AlignType.TopRight, referView: view, size: tableViewSize)
        bottomView.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: bottomViewHeight))
    }
    
    
    //MARK: - table view 数据源方法和代理方法
    //分2组
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    //每组1行
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return self.comments?.count ?? 0
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            return self.headerView
        }
        return nil
    }
    
    
    //cell的样式
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cellID = status?.cellID()
            let cell = tableView.dequeueReusableCellWithIdentifier(cellID!) as! CZStatusCell
            cell.status = status
            cell.delegate = self
            return cell
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("commentCell") as! CZCommentCell
            cell.comment = self.comments![indexPath.row]
            return cell
        }
    }
    
    //行高
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if status?.rowHeight != nil {
                return status!.rowHeight!
            }
            
            let cellID = status!.cellID()
            let cell = tableView.dequeueReusableCellWithIdentifier(cellID) as! CZStatusCell
            let rowHeight = cell.rowHeight(status!)
            status?.rowHeight = rowHeight
            return rowHeight
        } else {
            
            let comment = self.comments?[indexPath.row]
            if comment?.rowHeight != nil {
                return comment!.rowHeight!
            } else {
                let cell = tableView.dequeueReusableCellWithIdentifier("commentCell") as! CZCommentCell
                return cell.rowHeight(comment!)
            }
        }
    }
    
    //MARK: - 懒加载
    
    
    private lazy var headerView: UIView = {
        let view = UIView()
        let btn = UIButton()
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(11)
        btn.contentMode = UIViewContentMode.Left
        btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        btn.addTarget(self, action: "loadComments", forControlEvents: UIControlEvents.TouchUpInside)
        btn.sizeToFit()
        view.addSubview(btn)
        
        btn.ff_AlignInner(type: ff_AlignType.CenterLeft, referView: view, size: nil, offset: CGPoint(x: 5, y: 3))
        return view
    }()
    
    ///tableView
    lazy var tableView: UITableView = {
        let tableView = UITableView()
        
        //代理
        tableView.delegate = self
        tableView.dataSource = self
        //注册cell
        tableView.registerClass(CZStatusNormalCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusNormalCell.rawValue)
        tableView.registerClass(CZStatusForwardCell.self, forCellReuseIdentifier: CZStatusCellReuseIdentifier.StatusForwardCell.rawValue)
        tableView.registerClass(CZCommentCell.self, forCellReuseIdentifier: "commentCell")
        
        tableView.estimatedRowHeight = 200

        tableView.showsInfiniteScrolling = false
        tableView.addInfiniteScrollingWithActionHandler({ () -> Void in
            //加载更多评论
            self.loadComments()
        })
        
        return tableView
    }()
    
    ///底部栏
    private lazy var bottomView: CZStatusBottomView = {
        let bottomView = CZStatusBottomView()
        bottomView.forwardButton.addTarget(self, action: "forwardButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        bottomView.commentButton.addTarget(self, action: "commentButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        bottomView.zanButton.addTarget(self, action: "zanButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        bottomView.zanButton.setImage(UIImage(named: "timeline_icon_like"), forState: UIControlState.Selected)
        return bottomView
    }()
    
    
    
    
    
//MARK:- 监听按钮的点击
    ///监听底部转发按钮的点击
    func forwardButtonClick() {
        print("forwardButtonClick")
        //let forwardVc = CZForwardViewController()
        let forwardVc = CZComposeViewController(controllerType: CZComposeViewControllerType.Repost)
        forwardVc.status = status
        self.presentViewController(UINavigationController(rootViewController: forwardVc), animated: true, completion: nil)
    }
    
    ///监听底部评论按钮的点击
    func commentButtonClick() {
        print("commentButtonClick")
        
        let commentVc = CZComposeViewController(controllerType: CZComposeViewControllerType.Comment)
        commentVc.status = status
        //发表评论后的回调
        commentVc.commentCallBack = {
            self.commentViewControllerDidFinishComment()
        }
        self.presentViewController(UINavigationController(rootViewController: commentVc), animated: true, completion: nil)
    }
    
    ///监听底部点赞按钮的点击
    func zanButtonClick(btn: UIButton) {
        btn.selected = !btn.selected
        if btn.selected == true {
            status?.attitudes_count += 1
        } else {
             status?.attitudes_count -= 1
        }
        tableView.reloadData()
    }

}






extension CZStatusDetailController: CZStatusCellDelegate {
    func statusCellDidReteewedStatusBackgroundBtnClick(status: CZStatus) {
        let reteewedVc = CZStatusDetailController()
        reteewedVc.status = status
        reteewedVc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(reteewedVc, animated: true)
        
    }
    ///刷新评论
    func commentViewControllerDidFinishComment() {
        self.loadComments()
    }
}